/**
 * 
 */
package ch.baeni.jee.web;

import javax.annotation.PostConstruct;
import javax.enterprise.inject.Model;
import javax.enterprise.inject.Produces;
import javax.faces.application.FacesMessage;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import ch.baeni.jee.model.User;
import ch.baeni.jee.service.UserService;

/**
 * @author Benjamin
 *
 */
//@ManagedBean(name="registrationBean")
@RequestScoped
@Model
public class RegistrationBean extends AbstractBean {
	
	private static final String SUCCESS = "login";
	private static final String ERROR   = "registration";

	private String pwConfirm;
	
	@Inject
	private FacesContext facesContext;
	
	@Inject
	private UserService userService;

	@Produces
	@Named
	private User user;
	
	public User getUser() {
		if (user.getGender() == null){
			user.setGender("M");
		}
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	
	@PostConstruct
	public void initNewUser(){
		user = new User();
	}
	/**
	 * Speichert einen User in die Datenbank
	 * @return String für die Navigation
	 */
	public String save() {
		user.setActive(0);
		user.setRole("user");
		try {
			userService.saveUser(user);
			FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_INFO, "Value stored in Database", "Submit successful");
			facesContext.addMessage(null, m);
			initNewUser();
			return SUCCESS;
		} catch (Exception e) {
			String errorMessage = null;
            FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, "Submit successful");
            facesContext.addMessage(null, m);
			return ERROR;
		}
	}

	public String getPwConfirm() {
		return pwConfirm;
	}
	public void setPwConfirm(String pwConfirm) {
		this.pwConfirm = pwConfirm;
	}
}
